# Created by yang
from types import FunctionType

from django.template.library import Library

register = Library()

@register.inclusion_tag('niubin/change_list_table.html')
def show_result_list(cl):
    """
    :param cl: 定义在v1.py中的ChangeList对象,对象中有 list_display, data_list, model_config三个变量
    """
    def headers():
        if not cl.list_display:
            yield cl.model_config.model_class._meta.model_name
        for v in cl.list_display:

            yield v(cl.model_config, isheader=True) if isinstance(v, FunctionType) else cl.model_config.model_class._meta.get_field(
                v).verbose_name

    def body():
        for row in cl.data_list:
            if not cl.list_display:
                yield [str(row), ]
            yield [i(cl.model_config, obj=row) if isinstance(i, FunctionType) else getattr(row, i) for i in cl.list_display]


    return {
            "headers": headers(),
            "body": body(),
        }

@register.inclusion_tag('niubin/change_list_actions.html')
def show_actions(cl):

    def get_actions(cl):
        for action in cl.model_config.get_actions():
            yield action.__name__,action.short_desc

    return {"actions":get_actions(cl)}